/**
 * 语音模块，负责处理单词发音和例句发音
 */
export const useSpeechModule = (wordData) => {
  /**
   * 播放单词发音
   * @param {string} accent - 发音口音类型，'us'或'uk'
   */
  const playPronunciation = (accent = 'us') => {
    if (!wordData.currentWord?.content) return;
    
    // 默认使用美式发音，可选择英式发音
    const utterance = new SpeechSynthesisUtterance(wordData.currentWord.content);
    utterance.lang = accent === 'uk' ? 'en-GB' : 'en-US';
    
    const voices = window.speechSynthesis.getVoices();
    let preferredVoice;
    
    if (accent === 'uk') {
      // 寻找英式女声，然后是任何英式声音
      preferredVoice = voices.find(v => v.lang.includes('en-GB') && v.name.includes('Female')) ||
                      voices.find(v => v.lang.includes('en-GB'));
    } else {
      // 寻找美式女声，然后是任何美式声音
      preferredVoice = voices.find(v => v.lang.includes('en-US') && v.name.includes('Female')) ||
                      voices.find(v => v.lang.includes('en-US'));
    }
    
    // 如果找不到特定口音的声音，使用任何英语声音
    if (preferredVoice) {
      utterance.voice = preferredVoice;
    } else {
      const anyEnglishVoice = voices.find(v => v.lang.includes('en'));
      if (anyEnglishVoice) utterance.voice = anyEnglishVoice;
    }
    
    Object.assign(utterance, {
      volume: 1,
      rate: 0.9,
      pitch: 1
    });
    
    window.speechSynthesis.speak(utterance);
  };
  
  /**
   * 播放例句
   */
  const playExampleSentence = () => {
    playSpeech(wordData.currentWord?.example?.text);
  };
  
  /**
   * 播放相关单词
   * @param {string} word - 要播放的单词
   */
  const playRelatedWord = (word) => {
    playSpeech(word);
  };
  
  /**
   * 通用语音播放函数
   * @param {string} text - 要播放的文本
   */
  const playSpeech = (text) => {
    if (!text || !('speechSynthesis' in window)) return;

    const utterance = new SpeechSynthesisUtterance(text);
    utterance.lang = 'en-US';
    
    const voices = window.speechSynthesis.getVoices();
    const englishVoice = voices.find(voice => 
      voice.lang.includes('en') && voice.name.includes('Female')
    ) ?? voices.find(voice => voice.lang.includes('en'));
    
    if (englishVoice) {
      utterance.voice = englishVoice;
    }
    
    Object.assign(utterance, {
      volume: 1,
      rate: 0.9,
      pitch: 1
    });
    
    window.speechSynthesis.speak(utterance);
  };

  return {
    playPronunciation,
    playExampleSentence,
    playRelatedWord,
    playSpeech
  };
}; 